#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
  Резервное копирование
"""

import logging
import os
import StringIO
import tarfile
import gzip
#import zlib
from engine import settings
from engine.data import feedback
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

# enable info logging by the app
logging.getLogger().setLevel(logging.INFO)

def tarPath(root, name, tfile):
  """Архивируем путь в tar
  Args:
    root: a directory;
    name: entry in root
    tfile: tarfile object.
  """
  info = tarfile.TarInfo()
  
  if root:
      path = root + '/' + name
  else:
      path = name
  if os.path.isdir(path):
      entries = os.listdir(path) 
      for entry in entries:
          fullPath = path + '/' + entry
          if os.path.isdir(fullPath): 
              info.size = 0
              info.name = fullPath
              info.type = tarfile.DIRTYPE
              tfile.addfile(info)
              tarPath('', fullPath, tfile)
          else: # is file
              f = file(fullPath,'rb')
              info.type = tarfile.REGTYPE
              info.size = os.path.getsize(fullPath);
              info.name = fullPath
              info.mtime = os.path.getmtime(fullPath);
              tfile.addfile(info, f)

def gztarfile(path):
  """Архивируем и сжимаем все файлы и директории по указанному пути.
  """
  tarbuf = StringIO.StringIO()
  tar = tarfile.TarFile(mode = 'w', fileobj = tarbuf)
  #tar.add(path)
  tarPath('', path, tar)
  tar.close()
  zbuf = StringIO.StringIO() 
  zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 9)
  zfile.write(tarbuf.getvalue())
  zfile.close() 
  return zbuf.getvalue()

class BackupHandler(webapp.RequestHandler):
  def get(self):
    rootpath = '.'
    logging.info('Backup started.')
    dir = os.path.dirname(__file__)
    filename = 'backup' # + datenow

    self.redirect(settings.ROOT + 'admin/backup')
    self.response.set_status(200)
    self.response.headers['Content-Type'] = 'application/octet-stream'  
    self.response.headers.add_header('Content-Type', 'application/x-compressed')
    self.response.headers['Content-Disposition'] = 'attachment;filename=' + filename
    self.response.out.write(gztarfile(rootpath))